package batchprocessor;

import java.util.ArrayList;
import java.util.List;

public class Batch {

    String wkdir;
    List<Command> commands;

    public Batch() {
        commands = new ArrayList<>();
    }
    
    public String getWorkingdir() {
        return wkdir;
    }

    public void setWkdir(String dir) {
        wkdir = dir;
    }

    public void addCommand(Command command) {
        commands.add(command);
    }

    public void start() throws ProcessException {

        int flag;
        
        // Start all of the commands
        while (!commands.isEmpty()) {
            // Figure out if there are any file dependencies
            for (Command command0 : commands) {
                flag = 1;
                for (Command command1 : commands) {

                    if (command0.getId().equals(command1.getId())) {
                        continue;
                    }

                    // Check all the files to see if there are any dependencies
                    if (command0.getInFile().equals(command1.getOutFile())) {
                        flag = 0;
                    }
                }

                // Do not execute in parallel
                if (flag == 1) {
                    command0.start(wkdir);
                    command0.finish();
                    
                    // Set command for removal
                    command0.setId("Null");
                }
            }

            for (int i = 0; i < commands.size(); i++) {

                if (commands.get(i).getId().equals("Null")) {
                    commands.remove(i);
                }
            }
        }
    }
    
public void finish() throws ProcessException {

        // Wait for all of the commands to finish
        for(Command command: commands){
            command.finish();
        }
    }
}